import 'dotenv/config';
import type { VercelRequest, VercelResponse } from '@vercel/node';
import { PageRequest } from '../../dto/page/index';
import { getRandomMaterials, getPageMaterials } from '../../service/material/MaterialService';
import { errorWithCodeAndMsg, successWithData } from '../../util/result';
import { BizError } from '../../enums/ErrorsEnum';
import { handleException } from '../../util/exception';
export default async (_req: VercelRequest, _res: VercelResponse) => {

  return await handleException(_req,_res,async (request,response) => {
    const { method } = request;
    if (method === 'POST') {
      const { keyword, page, size } = request.body as PageRequest;
      if (page < 1 || size < 1)
        throw new BizError('页数和每页数量必须大于0');
      const result = await getPageMaterials({ keyword, page, size });
      return response.json(successWithData(result));
    } else if (method === 'GET') {
      const { num } = request.query;
      if(parseInt(num as string)<0)
        throw new BizError('数量必须大于0');
      const data = await getRandomMaterials(parseInt(num as string));
      return response.json(successWithData(data));
    }
    else {
      return response.json(errorWithCodeAndMsg(405, 'Method Not Allowed'));
    }
  })

  
}
